package com.sky.aspect;


import com.sky.aop.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
//execution(* com.sky.mapper.*.*(..))
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.aop.AutoFill)")
    public void autoFillPointCut(){}


    @Around("autoFillPointCut()&&@annotation(autoFill)")
    public Object autoFill(ProceedingJoinPoint pjp, AutoFill autoFill) throws Throwable{
        //获取方法参数
        Object[] args = (Object[]) pjp.proceed();
       Object pojo= args[0];
       //
        OperationType type=autoFill.value();

        //判断类型
        Class c = pojo.getClass();

        //如果是新增
        if (type == OperationType.INSERT) {
            //时间
            Field createTime = c.getDeclaredField("createTime");
            createTime.setAccessible(true);
            createTime.set(pojo, LocalDateTime.now());

            //创建人
            Field createUser = c.getDeclaredField("createUser");
            createUser.setAccessible(true);
            createUser.set(pojo, BaseContext.getCurrentId());

        }
        //修改时间
        Field updateTime = c.getDeclaredField("updateTime");
        updateTime.setAccessible(true);
        updateTime.set(pojo,LocalDateTime.now());

        //修改人
        Field updateUser = c.getDeclaredField("updateUser");
        updateUser.setAccessible(true);
        updateUser.set(pojo, BaseContext.getCurrentId());

        Object result = pjp.proceed(args);
        return  result;


    }
}
